<template>
  <div class="app-container">
    <vxe-toolbar>
      <template #buttons>
        <vxe-button status="primary" @click="handleEdit(null)">新增</vxe-button>
        <vxe-button status="primary" @click="handleQuery()">刷新</vxe-button>
          <vxe-input v-model="filterName" type="search" placeholder="模板搜索" style="margin-left: 10px" @keyup="searchEvent"></vxe-input>
      </template>
    </vxe-toolbar>
    <vxe-table
        border
        size="small"
        ref="template"
        :height="windowHeight-200"
        :loading="loading"
        :row-config="{isCurrent: true, isHover: true}"
        :checkbox-config="{labelField: 'templateID', highlight: true, range: true}"
        :data="templateTableData"
    >
      <vxe-column type="checkbox" field="templateID" title="ID" width="100"></vxe-column>
      <vxe-column field="templateCode" title="模板编码"></vxe-column>
      <vxe-column field="templateName" title="模板名称"></vxe-column>
      <vxe-column field="templateType" title="模板类型" :formatter="formatType" ></vxe-column>
      <vxe-column field="categoryID" title="所属分类"  :formatter="formatCate" ></vxe-column>
      <vxe-column field="allowBestFitColumns" title="审核流程"  :formatter="formatProce" ></vxe-column>
      <vxe-column field="memo" title="备注"></vxe-column>
      <vxe-column title="操作" width="250" fixed="right">
        <template #default="{ row }">
          <vxe-button status="success" size="mini" @click="handleRight(row)">权限</vxe-button>
          <vxe-button status="success" size="mini" @click="handleEdit(row)">编辑</vxe-button>
          <vxe-button status="danger" size="mini" @click="handleDelete(row)">删除</vxe-button>
        </template>
      </vxe-column>
    </vxe-table>
  </div>
</template>

<script lang="ts">
import {defineComponent, onBeforeMount, reactive, ref, toRefs} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import EditMenu from '/@/views/system/menu/component/editMenu.vue';
// import EditTemplate from '/@/views/linkoo/templates/edit.vue';
import {deleteTemplate, getTemplateList} from "/@/api/linkoo/templates";
import {useRouter} from 'vue-router';
import {listCateMenu} from "/@/api/linkoo/category";
import XEUtils from "xe-utils";

export default defineComponent({
  name: 'apiV1SystemAuthMenuList',
  components: { EditMenu },
  setup() {
    const router = useRouter()
    const editMenuRef = ref();
    const template = ref();
    const state = reactive({
      windowHeight: document.documentElement.clientHeight,
      queryParams:{
        title:"",
        component:""
      },
        cate:[],
      selectRow:"",
        filterName:"",
        templatetype: [{ label: '表单', value: 1 }, { label: '报表', value: 2 }, { label: '直改表', value: 3 }, { label: '动态表', value:4 }],
        process:[{value: 0,label: '不启用',},{value: 1,label: '直接审核',},{value: 2,label: '内部流程',disabled: true,},{value: 3,label: '外部流程',},{value: 5,label: '高级流程',}],
      loading:false,
      showTableEdit:false,
      submitLoading:false,
      templateTableData:[],
      templateTableDatas:[],
    });
    // const {proxy} = getCurrentInstance() as any;
    const acType = ref('add')
    // 打开新增菜单弹窗
    const onOpenAddMenu = (row:any) => {
      acType.value = 'add'
      editMenuRef.value.openDialog(row);
    };
    // 打开编辑菜单弹窗
    const onOpenEditMenu = (row: any) => {
      acType.value='edit'
      editMenuRef.value.openDialog(row);
    };
    // 删除当前行
    const onTabelRowDel = (row: any) => {
      ElMessageBox.confirm(`此操作将永久删除菜单：“${row.title}”, 是否继续?`, '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
            // delMenu(row.id).then(()=>{
            //   ElMessage.success('删除成功');
            //   proxy.$refs['editMenuRef'].resetMenuSession()
            //   menuList();
            // })
          })
          .catch(() => {});
    };

    onBeforeMount(()=>{
      templateList()
    });
    const handleQuery=() => {
      templateList();
    };
      const searchEvent = () => {
          const filterVal = String(state.filterName).trim().toLowerCase()
          if (filterVal) {
              const filterRE = new RegExp(filterVal, 'gi')
              const searchProps = ['templateCode', 'templateName']
              const rest = state.templateTableDatas.filter(item => searchProps.some(key => String(item[key]).toLowerCase().indexOf(filterVal) > -1))
              state.templateTableData = rest.map(row => {
                  return Object.assign({}, row)
              })
          } else {
              state.templateTableData = state.templateTableDatas
          }
      };
    const templateList = ()=>{
        listCateMenu(state.queryParams).then(response => {
            state.cate = XEUtils.toTreeArray(response.data.list);
            getTemplateList(state.queryParams).then(res=>{
                state.templateTableData = res.data.templateList;
                state.templateTableDatas = res.data.templateList;
            })
        });


    };
    const formatProce=({ cellValue }) => {
          const item = XEUtils.find( state.process,item=>item.value===cellValue)
          return item ? item.label : cellValue
      }
    const formatType=({ cellValue }) => {
          const item = XEUtils.find( state.templatetype,item=>item.value===cellValue)
          return item ? item.label : cellValue
      }
    const formatCate=({ cellValue }) => {
          const item = XEUtils.find( state.cate,item=>item.id===cellValue)
          return item ? item.title : cellValue
      }
    const handleEdit = (row: any) => {
      if (row === null) {
        row = {}
        row.templateCode = '_addNewTemplate_'
      }
      router.push('/templates/edit/' + row.templateCode)
    };
    const handleRight = (row: any) => {
      router.push('/right/edit/' + row.templateID)
    };
    const flash = () => {
    };
    const handleTable = () => {
    };
    const handleRule = () => {
    };
    const handleDelete = (row:any) => {
      deleteTemplate
      ElMessageBox.confirm(`此操作将永久删除模板：“${row.templateName}”, 是否继续?`, '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteTemplate(row.templateID).then(()=>{
          ElMessage.success('删除成功');
          handleQuery()
        })
      }).catch(() => {});
    };
    return {
      editMenuRef,template,
      handleEdit,
      handleTable,
      handleRule,
      flash,
      onOpenAddMenu,searchEvent,
      onOpenEditMenu,formatProce,
      onTabelRowDel,formatType,
      handleDelete,formatCate,
      templateList,
      handleRight,
      handleQuery,
      ...toRefs(state),
      acType
    };
  },
});
</script>
